<template>
  <div class="page-root">
    <BasePanel>
      <BaseSearch
        :search="searchProps"
        @searchData="updateTable"
        @resetData="updateTable"
      />
      <div class="table-top-wrap">
        <div class="table-title">
          <span>列表</span>
        </div>
        <div class="btn-gruop">
          <a-button type="primary" icon="plus" ghost @click="handleAdd"
            >新增</a-button
          >
        </div>
      </div>
      <BaseTable
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :scroll="{ x: 1000 }"
      >
        <template slot="time" slot-scope="{ record }">
          <div>
            <div>{{ record.startTime }} - {{ record.endTime }}</div>
          </div>
        </template>
        <template slot="status" slot-scope="{ record, index }">
          <a-switch
            :checked="record.isChecked"
            checked-children="开启"
            un-checked-children="关闭"
            :loading="record.loading"
            @change="onChange(record, index)"
            style="width: 70px"
          />
        </template>
        <template slot="risk" slot-scope="{ record, index }">
          <a-switch
            :checked="record.risk"
            checked-children="开启"
            un-checked-children="关闭"
            :loading="record.loading"
            @change="onChange2(record, index)"
            style="width: 70px"
          />
        </template>
        <template slot="operation" slot-scope="{ record }">
          <span class="primary" @click="handleRadar(record)">雷达</span>
          <a-divider type="vertical" />
          <span class="primary" @click="handleEdit(record)">编辑</span>
          <a-divider type="vertical" />
          <span class="primary" @click="handleAdjust(record)">过滤器配置</span>
          <a-divider type="vertical" />
          <span class="primary" @click="handleCheck(record)">城市配置</span>
        </template>
      </BaseTable>
      <div v-show="dataSource.length > 0" class="page-footer">
        <BasePagination :page-key.sync="pageKey" :get-list="tableInit" />
      </div>
      <a-modal
        title="单价配置"
        :width="700"
        @ok="handleModalConfirm"
        @cancel="handleModalCancel"
        :confirm-loading="modalLoading"
        :visible="praice_visible"
      >
        <a-form-model
          ref="form"
          :model="form"
          :rules="formRules"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
        >
          <div style="color: red">*选择城市的单价将统一设置</div>
          <div style="display: flex">
            <div>当前选择：</div>
            <div
              style="margin-left: 5px"
              v-for="(item, index) in selectedRows"
              :key="index"
            >
              {{ item.cityName }}
            </div>
          </div>
          <a-form-model-item label="开通城市单价" prop="price">
            <a-input-number
              v-model="form.price"
              :min="0"
              placeholder="请输入"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </BasePanel>
    <radar
      :visible="radarShow"
      :default="defaultObj"
      @success="successForm"
      @close="closeradar"
    />
    <FormModal
      :visible="formShow"
      :default="defaultObj"
      @success="successForm"
      @close="closeForm"
    />
    <OpenModal
      :visible="openShow"
      :default="defaultObj"
      @success="successOpen"
      @close="closeOpen"
    />
    <AdjustModal
      :visible="adjustShow"
      :id="id"
      :default="defaultObj"
      @success="successForm"
      @close="closeAdjust"
    />
    <TableModal
      ref="table_modal_ref"
      :visible="tableShow"
      :isUpdate="isUpdate"
      :id="id"
      @open="handleOpen"
      @mask="handleMask"
      @mask_list="handleMask_list"
      @mask_list2="handleMask_list2"
      @close="closeTable"
    />
  </div>
</template>

<script>
import { searchProps, columns } from "./option.js";
import * as Ajax from "@/api/institution";
import radar from "./radar";
import FormModal from "./form";
import OpenModal from "./open";
import AdjustModal from "./adjust";
import TableModal from "./table";
export default {
  components: {
    FormModal,
    OpenModal,
    AdjustModal,
    TableModal,
    radar,
  },
  data() {
    return {
      modalLoading: false,
      form: {
        price: "",
      },
      formRules: {
        price: {
          required: true,
          message: "请输入",
          trigger: ["blur", "change"],
        },
      },
      searchProps,
      searchForm: {},
      columns,
      loading: true,
      dataSource: [],
      pageKey: {
        pageSize: 10,
        total: 1,
        current: 1,
      },
      radarShow: false,
      formShow: false,
      openShow: false,
      adjustShow: false,
      defaultObj: {},
      id: "",
      tableShow: false,
      institutionId: "",
      institutionType: "",
      isUpdate: false,
      selectedRows: [],
      praice_visible: false,
    };
  },
  created() {
    this.tableInit();
  },
  methods: {
    handleModalCancel() {
      this.$refs.form.resetFields();
      this.selectedRows = [];
      this.form.price = "";
      this.praice_visible = false;
    },
    handleOpen(data) {
      this.defaultObj = {
        ...data,
        planId: this.id,
        institutionId: this.institutionId,
        institutionType: this.institutionType,
      };
      this.openShow = true;
    },
    handleMask(data) {
      const params = {
        ...data,
        planId: this.id,
        institutionId: this.institutionId,
        institutionType: this.institutionType,
        prevent: 0,
      };
      Ajax.togglePlanCityList(params).then(({ success }) => {
        if (success) {
          this.$message.success("屏蔽成功");
          this.isUpdate = !this.isUpdate;
        }
      });
    },
    handleMask_list(data_list) {
      const that = this;
      data_list.forEach((item) => {
        item.planId = this.id;
        item.institutionId = this.institutionId;
        item.institutionType = this.institutionType;
        item.prevent = 0;
      });
      const selectedRows = data_list.filter((item) => item.cityName !== "全国");
      console.log(data_list);
      this.$confirm({
        title: "批量屏蔽",
        content: `确定要进行批量屏蔽吗？当前共选择${data_list.length}个城市`,
        onOk() {
          // const clueIdList = that.selectedRows.map((it) => it.id);
          Ajax.preventplancitylist({ selectedRows })
            .then(({ success }) => {
              if (success) {
                that.$message.success("屏蔽成功");
                that.isUpdate = !that.isUpdate;
                that.$refs.table_modal_ref.selectedRows = [];
              }
            })
            .finally(() => {
              that.false = true;
              that.$refs.table_modal_ref.selectedRows = [];
            });
        },
        onCancel() {},
      });
    },
    async handleModalConfirm() {
      const that = this;
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          that.modalLoading = true;
          that.selectedRows.forEach((item) => {
            item.price = that.form.price;
          });
          // console.log(that.selectedRows);
          const res = await Ajax.preventplancitylist({
            selectedRows: that.selectedRows,
          }).finally(() => {
            that.modalLoading = false;
          });
          if (res.success) {
            that.$message.success("开通成功");
            that.selectedRows = [];
            that.isUpdate = !that.isUpdate;
            that.form.price = "";
            that.praice_visible = false;
          }
        }
      });
      // console.log(this.selectedRows);

      // Ajax.preventplancitylist({ selectedRows: this.selectedRows })
      //   .then(({ success }) => {
      //     if (success) {
      //       that.$message.success("开通成功");
      //       that.isUpdate = !that.isUpdate;
      //       that.$refs.table_modal_ref.selectedRows = [];
      //     }
      //   })
      //   .finally(() => {
      //     that.false = true;
      //     that.$refs.table_modal_ref.selectedRows = [];
      //   });
    },
    handleMask_list2(data_list) {
      const that = this;
      data_list.forEach((item) => {
        item.planId = this.id;
        item.institutionId = this.institutionId;
        item.institutionType = this.institutionType;
        item.prevent = 1;
      });
      this.selectedRows = data_list.filter((item) => item.cityName !== "全国");
      this.$refs.table_modal_ref.selectedRows = [];
      this.$confirm({
        title: "批量开通",
        content: `确定要进行批量开通吗？当前共选择${data_list.length}个城市`,
        onOk() {
          that.praice_visible = true;
        },
        onCancel() {},
      });
    },
    successOpen() {
      this.isUpdate = !this.isUpdate;
    },
    updateTable(params = {}) {
      this.searchForm = { ...params };
      this.pageKey = this.$options.data().pageKey;
      this.tableInit();
    },
    onChange(record, index) {
      const _this = this;
      this.$confirm({
        title: "执行提示",
        content: "请确认是否执行？",
        onOk() {
          _this.dataSource[index].loading = true;
          const params = {
            id: record.id,
            status: !_this.dataSource[index].isChecked ? 0 : 1,
          };
          Ajax.editPlanList(params)
            .then(({ success }) => {
              if (success) {
                _this.$message.success("操作成功");
                _this.tableInit();
              }
            })
            .finally(() => {
              _this.dataSource[index].loading = false;
            });
        },
        onCancel() {
          _this.dataSource[index].loading = false;
        },
      });
    },
    onChange2(record, index) {
      const _this = this;
      this.$confirm({
        title: "执行提示",
        content: "请确认是否执行？",
        onOk() {
          _this.dataSource[index].loading = true;
          const params = {
            id: record.id,
            risk: !_this.dataSource[index].risk ? 1 : 0,
          };
          Ajax.editPlanList(params)
            .then(({ success }) => {
              if (success) {
                _this.$message.success("操作成功");
                _this.tableInit();
              }
            })
            .finally(() => {
              _this.dataSource[index].loading = false;
            });
        },
        onCancel() {
          _this.dataSource[index].loading = false;
        },
      });
    },
    // table 初始化
    tableInit() {
      this.loading = true;
      const { current, pageSize } = this.pageKey;
      const params = { pageNum: current, pageSize, ...this.searchForm };
      Ajax.getPlanList(params)
        .then((res) => {
          const { data, totalCount } = res;
          this.dataSource = Array.isArray(data)
            ? data.map((it) => {
                return {
                  ...it,
                  isChecked: it.status === 0,
                  risk: it.risk === 1,
                  loading: false,
                };
              })
            : [];
          this.pageKey.total = totalCount;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleAdd() {
      this.formShow = true;
    },
    handleRadar(record) {
      if (record.riskConfigVO) {
        const {
          notRisk,
          sexM0,
          loanAction,
          threeLoanCount,
          repayRate,
          loanOverOrderCount,
          oneOfRepay,
          repayOrderCount,
          currentOverOrderCount,
          oneRepayLoanAmount,
        } = record.riskConfigVO;
        const { id } = record;
        this.defaultObj = {
          planId: id,
          notRisk: notRisk,
          sexM0,
          loanAction,
          repayRate,
          threeLoanCount,
          loanOverOrderCount,
          oneOfRepay: oneOfRepay,
          repayOrderCount,
          currentOverOrderCount,
          oneRepayLoanAmount,
        };
      } else {
        const { id } = record;
        this.defaultObj = {
          planId: id 
        };
      }
      this.radarShow = true;
    },
    // 编辑
    handleEdit(record) {
      const {
        id,
        dayQuantity,
        endTime,
        institutionId,
        planName,
        startTime,
        status,
        type,
        weight,
        towFactorSwitch,
      } = record;
      this.defaultObj = {
        id,
        dayQuantity,
        endTime,
        institutionId,
        planName,
        startTime,
        status: status === 0,
        type: String(type),
        weight,
        towFactorSwitch: towFactorSwitch ? true : false,
      };
      console.log(this.defaultObj.towFactorSwitch);
      this.formShow = true;
    },
    handleAdjust(record) {
      const {
        id,
        preventChannelId,
        meetConditions,
        planConditionConfigVOList,
      } = record;
      this.id = id;
      this.defaultObj = {
        preventChannelId,
        meetConditions,
        planConditionConfigVOList,
      };
      this.adjustShow = true;
    },
    handleCheck(record) {
      const { id, institutionId, type } = record;
      this.id = id;
      this.institutionId = institutionId;
      this.institutionType = type;
      this.tableShow = true;
    },
    successForm() {
      this.tableInit();
      this.closeForm();
    },
    closeForm() {
      this.formShow = false;
      this.defaultObj = {};
    },
    closeradar() {
      this.radarShow = false;
      this.defaultObj = {};
    },
    closeOpen() {
      this.openShow = false;
      this.defaultObj = {};
    },
    closeAdjust() {
      this.adjustShow = false;
      this.id = "";
      this.defaultObj = {};
    },
    closeTable() {
      this.tableShow = false;
      this.defaultObj = {};
      this.id = "";
      this.institutionId = "";
      this.institutionType = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.table-wrap {
  margin-top: 16px;
}

.table-top-wrap {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.table-img {
  cursor: pointer;
  max-height: 20px;
  max-width: 100px;
}

.table-title {
  flex: 1;

  span {
    line-height: 32px;
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;

    &::before {
      content: "";
      display: block;
      width: 3px;
      height: 18px;
      background-color: #1890ff;
      margin-right: 8px;
      position: relative;
      top: -1px;
    }
  }
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;

  & > button {
    margin-left: 12px;

    &:first-child {
      margin-left: 0;
    }
  }
}
</style>
